<template>
  <uni-nav-bar :border="false" fixed :title="title" />
  <view class="container">
    <view class="bg-#fff">
      <view class="flex pt-20rpx mx-32rpx items-center gap-32rpx">
        <image
          :src="merchantInfo?.storeLogo"
          mode="aspectFill"
          class="w-100rpx h-100rpx rounded-50%"
        ></image>
        <view v-if="merchantLoading">加载中...</view>
        <view v-else>{{
          merchantInfo?.merchantName || storeStore.merchantName || "未选择店铺"
        }}</view>
      </view>
      <view
        class="payment flex items-center justify-center gap-32rpx bg-amber mt-20rpx"
        @click="goToQrCode"
      >
        <image src="/static/icon/skm.png" class="w-88rpx h-88rpx"></image>
        <view class="text-40rpx font-bold color-#fff">收款码</view>
      </view>
    </view>
    <view class="operating mt-20rpx bg-#fff px-32rpx py-20rpx">
      <view class="flex justify-between items-end gap-16rpx">
        <view>经营数据</view>
        <view class="color-#9c9c9c text-24rpx flex-1">
          截止到{{ dateUtils.toChinese() }}
        </view>
        <view class="color-#ffab00" @click="handleMore">更多</view>
      </view>
      <view class="text-28rpx font-bold text-center mt-20rpx"
        >今日店铺积分</view
      >
      <view class="flex justify-center mt-20rpx mb-20rpx">
        <NumberFlip :value="integral" />
      </view>
      <view class="text-24rpx flex justify-end">
        <!-- <view class="">今日等级奖励积分：0.00</view> -->
        <view
          class="color-#ffaf00 flex items-center"
          @click="showStatisticsInfo"
        >
          统计范围 <uni-icons type="info" color="#ffaf00"></uni-icons>
        </view>
      </view>
      <!-- 今日数据tab组件 -->
      <DataTabs
        :today-data="todayDataConfig.summary"
        :detail-data="todayDataConfig.details"
        @tab-change="handleTabChange"
      />
      <view class="statistical-time mt-20rpx text-24rpx color-#9c9c9c"
        >统计数据时间：今日 0:00~当前</view
      >
    </view>
    <view
      v-show="isUnfold"
      class="operating mt-20rpx bg-#fff px-32rpx py-20rpx"
    >
      <view>昨日数据</view>
      <view class="color-#9c9c9c text-24rpx">
        <!--昨天-->
        {{
          dateUtils.toChinese(new Date().getTime() - 24 * 60 * 60 * 1000) +
          "00:00:00~23:59:59"
        }}
      </view>
      <DataTabs
        class="mt-20rpx"
        :today-data="yesterdayDataConfig.summary"
        :detail-data="yesterdayDataConfig.details"
        @tab-change="handleYesterdayTabChange"
      />
    </view>
    <view
      class="mt-20rpx flex flex-col items-center justify-center bg-#fff p-16rpx"
      @click="handleToggleYesterdayData"
    >
      <uni-icons v-show="!isUnfold" color="#9c9c9c" type="down"></uni-icons>
      <uni-icons v-show="isUnfold" color="#9c9c9c" type="up"></uni-icons>
      <view v-show="!isUnfold" class="color-#9c9c9c text-24rpx">
        展开昨日数据
      </view>
      <view v-show="isUnfold" class="color-#9c9c9c text-24rpx"
        >收起昨日数据</view
      >
    </view>
    <!-- <view
      class="mt-20rpx flex gap-16rpx items-center justify-center bg-#fff p-32rpx color-#9c9c9c text-28rpx"
      @click="goToBusinessCalendar"
    >
      <image
        src="/static/icon/rili.png"
        class="w-48rpx h-48rpx mr-16rpx"
      ></image>
      <view>点击查看店铺经营月历</view>
      <uni-icons type="right" color="#9c9c9c"></uni-icons>
    </view> -->
    <!-- <view class="mt-20rpx bg-#fff p-16rpx" @click="goToCouponDetails"> -->
    <!--   <view class="text-28rpx">累计抵用券：25730.52</view> -->
    <!--   <view class="grid grid-cols-4 gap-16rpx"> -->
    <!--     <view class="coupons text-28rpx"> -->
    <!--       <view class="color-#9c9c9c">可用抵用券</view> -->
    <!--       <view>1087.37</view> -->
    <!--     </view> -->
    <!--     <view class="coupons text-28rpx"> -->
    <!--       <view class="color-#9c9c9c">冻结抵用券</view> -->
    <!--       <view>0.00</view> -->
    <!--     </view> -->
    <!--     <view class="coupons text-28rpx"> -->
    <!--       <view class="color-#9c9c9c">活动未生效</view> -->
    <!--       <view>0.00</view> -->
    <!--     </view> -->
    <!--     <view class="coupons text-28rpx"> -->
    <!--       <view class="color-#9c9c9c">潮客可激活</view> -->
    <!--       <view>3.91</view> -->
    <!--     </view> -->
    <!--     <view class="coupons text-28rpx"> -->
    <!--       <view class="color-#9c9c9c">推广佣金</view> -->
    <!--       <view>0.00</view> -->
    <!--     </view> -->
    <!--   </view> -->
    <!-- </view> -->
    <!-- <view class="mt-20rpx bg-#fff p-16rpx" @click="goToPointsDetail"> -->
    <!--   <view class="text-28rpx">积分：25730.52</view> -->
    <!--   <view class="grid grid-cols-3 gap-16rpx"> -->
    <!--     <view class="coupons text-28rpx"> -->
    <!--       <view class="color-#9c9c9c">补贴积分</view> -->
    <!--       <view>1087.37</view> -->
    <!--     </view> -->
    <!--     <view class="coupons text-28rpx"> -->
    <!--       <view class="color-#9c9c9c">会员积分</view> -->
    <!--       <view>0.00</view> -->
    <!--     </view> -->
    <!--     <view class="coupons text-28rpx"> -->
    <!--       <view class="color-#9c9c9c">潮客积分</view> -->
    <!--       <view>0.00</view> -->
    <!--     </view> -->
    <!--   </view> -->
    <!-- </view> -->
    <view
      class="mt-20rpx px-50rpx py-20rpx bg-#fff flex justify-between"
      @click="goToVoucherDetail"
    >
      <view class="flex gap-16rpx items-center">
        <!-- <view -->
        <!--   class="bg-#fabc02 rounded-50% w-40rpx h-40rpx flex justify-center items-center" -->
        <!-- > -->
        <!-- </view> -->
        <view class="flex-1 text-28rpx">抵用券明细</view>
      </view>
      <uni-icons type="right" color="#9c9c9c"></uni-icons>
    </view>
    <view
      class="mt-20rpx px-50rpx py-20rpx bg-#fff flex justify-between"
      @click="goToPointsDetail"
    >
      <view class="flex gap-16rpx items-center">
        <!-- <view -->
        <!--   class="bg-#fabc02 rounded-50% w-40rpx h-40rpx flex justify-center items-center" -->
        <!-- > -->
        <!-- </view> -->
        <view class="flex-1 text-28rpx">积分明细</view>
      </view>
      <uni-icons type="right" color="#9c9c9c"></uni-icons>
    </view>
    <view class="mt-20rpx px-50rpx py-20rpx bg-#fff flex justify-between">
      <view class="flex gap-16rpx items-center">
        <view
          class="bg-#fabc02 rounded-50% w-40rpx h-40rpx flex justify-center items-center"
        >
          <uni-icons type="sound-filled" color="#fff"></uni-icons>
        </view>
        <view class="flex-1 text-28rpx">系统公告</view>
      </view>
      <uni-icons type="right" color="#9c9c9c"></uni-icons>
    </view>

    <!-- 统计范围说明弹框 -->
    <uni-popup ref="statisticsPopup" type="center">
      <view class="statistics-modal">
        <!-- 弹框头部 -->
        <view class="modal-header">
          <text class="modal-title">统计范围</text>
          <uni-icons
            type="close"
            size="24"
            color="#666"
            @click="closeStatisticsInfo"
          ></uni-icons>
        </view>

        <!-- 弹框内容 -->
        <view class="modal-content">
          <view class="business-alliance">
            <text class="alliance-title">异业联盟</text>
          </view>

          <view class="order-types">
            <text class="order-type-item">扫码订单、</text>
            <text class="order-type-item">外卖订单、</text>
            <text class="order-type-item">自提订单、</text>
            <text class="order-type-item">到店订单</text>
          </view>

          <view class="order-types">
            <text class="order-type-item">线下汇款、</text>
            <text class="order-type-item">购房订单、</text>
            <text class="order-type-item">品牌使用费、</text>
            <text class="order-type-item">POS订单</text>
          </view>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { onShow } from "@dcloudio/uni-app";
import { useRequest } from "ahooks-vue";
import { dateUtils } from "@/utils/dayjs";
import NumberFlip from "./components/NumberFlip.vue";
import DataTabs from "./components/DataTabs.vue";
import { useStoreStore } from "@/store/modules/store";
import { useUserStore } from "@/store/modules/user";
import { getMerchantInfo } from "@/api/mine";
import { getMerchantHomeInfo } from "@/api/index";

// 使用 Pinia store
const storeStore = useStoreStore();
const userStore = useUserStore();

// 弹框引用
const statisticsPopup = ref(null);

const isUnfold = ref(false);
const title = "禧易宝商家端";

// 昨日数据是否已加载
const yesterdayDataLoaded = ref(false);

// 今日店铺积分
const integral = ref(0);

// 调试：接口调用计数
let apiCallCount = 0;

// 今日数据
const todayDataConfig = ref({
  summary: {
    totalRevenue: 0, // 营业额
    totalOrders: 0, // 订单数
    totalAmount: 0, // 金额
  },
  details: {
    // 营业额 Tab 的 6 项明细（selectType=2）
    onlineRevenue: 0, // 线上营业额
    onlineRefund: 0, // 退款线上金额
    offlineRevenue: 0, // 线下营业额
    offlineRefund: 0, // 退款线下金额
    bigRevenue: 0, // 大额营业额
    bigRefund: 0, // 退款大额金额
    // 订单数和金额的明细（暂时保留占位）
    receiptOrders: 0,
    refundOrders: 0,
    receiptAmount: 0,
    refundAmount: 0,
  },
});

// 昨日数据
const yesterdayDataConfig = ref({
  summary: {
    totalRevenue: 0, // 营业额
    totalOrders: 0, // 订单数
    totalAmount: 0, // 金额
  },
  details: {
    // 营业额 Tab 的 6 项明细（selectType=2）
    onlineRevenue: 0, // 线上营业额
    onlineRefund: 0, // 退款线上金额
    offlineRevenue: 0, // 线下营业额
    offlineRefund: 0, // 退款线下金额
    bigRevenue: 0, // 大额营业额
    bigRefund: 0, // 退款大额金额
    // 订单数和金额的明细（暂时保留占位）
    receiptOrders: 0,
    refundOrders: 0,
    receiptAmount: 0,
    refundAmount: 0,
  },
});

// 商户详细信息
const merchantInfo = ref(null);

// 获取商户详细信息
const { loading: merchantLoading, run: fetchMerchantInfo } = useRequest(
  () =>
    getMerchantInfo({
      merchantId: storeStore.storeId,
      userId: userStore.userInfo?.userId,
    }),
  {
    manual: true,
    onSuccess: (response) => {
      console.log("获取商户信息成功：", response);
      if (response?.data) {
        merchantInfo.value = response.data;
        // 更新 store 中的商户名称
        if (response.data.merchantName) {
          storeStore.currentStore = {
            ...storeStore.currentStore,
            merchantName: response.data.merchantName,
          };
        }
      }
    },
    onError: (error) => {
      console.error("获取商户信息失败：", error);
    },
  }
);
// 获取首页数据
const { loading: homeLoading, run: getMerchantHomeInfoRun } = useRequest(
  (params) => {
    // 提取 dateType（仅用于前端，不传给后端）
    const { dateType, ...apiParams } = params;

    // 将参数传递给接口
    const requestParams = {
      ...apiParams,
      merchantId: storeStore.storeId,
      userId: userStore.userInfo?.userId,
    };

    // 调用接口并将 selectType 和 dateType 附加到响应中
    return getMerchantHomeInfo(requestParams).then((res) => {
      return {
        ...res,
        _selectType: params.selectType,
        _dateType: dateType || "today", // 'today' 或 'yesterday'
      };
    });
  },
  {
    manual: true,
    onSuccess: (response) => {
      console.log("🔔 接口返回:", response);
      console.log("🔍 _selectType:", response._selectType);
      console.log("🔍 _dateType:", response._dateType);

      if (!response?.data) {
        console.warn("⚠️ response.data 为空");
        return;
      }

      const data = response.data;
      const selectType = response._selectType;
      const dateType = response._dateType || "today";
      console.log(
        "📌 当前处理的 selectType:",
        selectType,
        "dateType:",
        dateType
      );

      // 根据 dateType 选择要更新的配置对象
      const targetConfig =
        dateType === "yesterday" ? yesterdayDataConfig : todayDataConfig;

      if (selectType === 1) {
        // selectType=1: 汇总数据
        // a: 营业额, b: 订单数, c: 金额, d: 今日店铺积分
        const { a, b, c, d } = data;
        console.log("📊 selectType=1 数据:", { a, b, c, d });
        if (d !== undefined && dateType === "today") {
          integral.value = d;
        }
        targetConfig.value.summary = {
          totalRevenue: a || 0,
          totalOrders: b || 0,
          totalAmount: c || 0,
        };
        console.log(
          `✅ ${dateType} summary 已更新:`,
          targetConfig.value.summary
        );
      } else if (selectType === 2) {
        // selectType=2: 营业额明细（6项）
        // a: 线上营业额, b: 退款线上, c: 线下营业额
        // d: 退款线下, e: 大额营业额, f: 退款大额
        const { a, b, c, d, e, f } = data;
        console.log("📊 selectType=2 数据:", { a, b, c, d, e, f });
        targetConfig.value.details = {
          ...targetConfig.value.details,
          onlineRevenue: a || 0,
          onlineRefund: b || 0,
          offlineRevenue: c || 0,
          offlineRefund: d || 0,
          bigRevenue: e || 0,
          bigRefund: f || 0,
        };
        console.log(
          `✅ ${dateType} details 已更新:`,
          targetConfig.value.details
        );
      } else if (selectType === 3) {
        // selectType=3: 订单数明细（2项）
        // a: 收款订单数, b: 退款订单数
        const { a, b } = data;
        console.log("📊 selectType=3 数据:", { a, b });
        targetConfig.value.details = {
          ...targetConfig.value.details,
          receiptOrders: a || 0,
          refundOrders: b || 0,
        };
        console.log(
          `✅ ${dateType} 订单数明细已更新:`,
          targetConfig.value.details
        );
      } else if (selectType === 4) {
        // selectType=4: 金额明细（2项）
        // a: 收款金额, b: 退款金额
        const { a, b } = data;
        console.log("📊 selectType=4 数据:", { a, b });
        targetConfig.value.details = {
          ...targetConfig.value.details,
          receiptAmount: a || 0,
          refundAmount: b || 0,
        };
        console.log(
          `✅ ${dateType} 金额明细已更新:`,
          targetConfig.value.details
        );
      }
    },
    onError: (error) => {
      console.error("获取首页数据失败：", error);
    },
  }
);

// 刷新首页数据
const refreshData = async () => {
  console.log("🔄 刷新首页数据");

  // 从本地缓存恢复店铺信息
  storeStore.hydrateFromStorage();
  userStore.hydrateFromStorage();

  const todayDate = getTodayDate();

  // === 今日数据 ===
  // 先获取 selectType=1（汇总数据：营业额、订单数、金额、今日店铺积分）
  console.log("🚀 调用接口 selectType=1 (今日汇总)");
  await getMerchantHomeInfoRun({
    selectType: 1,
    selectTime: todayDate,
    dateType: "today",
  });

  // 等第一个接口完成后，再获取 selectType=2（营业额明细：6项数据）
  console.log("🚀 调用接口 selectType=2 (今日营业额明细)");
  await getMerchantHomeInfoRun({
    selectType: 2,
    selectTime: todayDate,
    dateType: "today",
  });

  // 检查是否有店铺信息
  if (!storeStore.hasStore) {
    console.warn("未找到店铺信息");
  } else {
    console.log("当前店铺：", storeStore.merchantName);

    // 获取商户详细信息
    if (storeStore.storeId && userStore.userInfo?.userId) {
      fetchMerchantInfo();
    }
  }
};

// 页面显示时刷新数据（包括切换店铺后返回）
onShow(() => {
  refreshData();
});

const handleMore = () => {
  uni.navigateTo({
    url: "/pages/mine/financialData/financialData",
  });
};

// 跳转到经营月历页面
const goToBusinessCalendar = () => {
  uni.navigateTo({
    url: "/pages/index/businessCalendar/businessCalendar",
  });
};

// 跳转到抵用券明细页面
const goToVoucherDetail = () => {
  uni.navigateTo({
    url: "/pages/index/voucherDetail/voucherDetail",
  });
};

// 跳转到积分明细页面
const goToPointsDetail = () => {
  uni.navigateTo({
    url: "/pages/index/vipPoints/vipPoints",
  });
};

// 显示统计范围说明
const showStatisticsInfo = () => {
  statisticsPopup.value?.open();
};

// 关闭统计范围说明弹框
const closeStatisticsInfo = () => {
  statisticsPopup.value?.close();
};

// 跳转到二维码页面
const goToQrCode = () => {
  uni.navigateTo({
    url: "/pages/index/qrCode/qrCode",
  });
};

// 处理展开/收起昨日数据
const handleToggleYesterdayData = async () => {
  isUnfold.value = !isUnfold.value;

  // 如果是展开且昨日数据还未加载，则加载昨日数据
  if (isUnfold.value && !yesterdayDataLoaded.value) {
    console.log("📅 首次展开昨日数据，开始加载...");
    const yesterdayDate = getYesterdayDate();

    // 获取昨日汇总数据
    console.log("🚀 调用接口 selectType=1 (昨日汇总)");
    await getMerchantHomeInfoRun({
      selectType: 1,
      selectTime: yesterdayDate,
      dateType: "yesterday",
    });

    // 获取昨日营业额明细
    console.log("🚀 调用接口 selectType=2 (昨日营业额明细)");
    await getMerchantHomeInfoRun({
      selectType: 2,
      selectTime: yesterdayDate,
      dateType: "yesterday",
    });

    // 标记昨日数据已加载
    yesterdayDataLoaded.value = true;
    console.log("✅ 昨日数据加载完成");
  }
};

// 获取昨天的日期字符串 (YYYY-MM-DD 格式)
const getYesterdayDate = () => {
  const yesterday = new Date();
  yesterday.setDate(yesterday.getDate() - 1);
  return dateUtils.format(yesterday, "YYYY-MM-DD");
};

// 获取今天的日期字符串 (YYYY-MM-DD 格式)
const getTodayDate = () => {
  return dateUtils.format(new Date(), "YYYY-MM-DD");
};

// 处理今日数据 tab 切换
const handleTabChange = async (tabIndex) => {
  console.log("🔄 今日数据 Tab 切换:", tabIndex);

  // 获取当前店铺 ID 和用户 ID
  const merchantId = Number(storeStore.storeId) || 0;
  const userId = userStore.userId || "";
  const selectTime = getTodayDate();

  // tabIndex: 0=营业额, 1=订单数, 2=金额
  if (tabIndex === 0) {
    // 点击"营业额" tab，调用 selectType=2
    console.log("🚀 调用接口 selectType=2 (营业额明细)");
    await getMerchantHomeInfoRun({
      selectType: 2,
      merchantId,
      userId,
      selectTime,
      dateType: "today",
    });
  } else if (tabIndex === 1) {
    // 点击"订单数" tab，调用 selectType=3
    console.log("🚀 调用接口 selectType=3 (订单数明细)");
    await getMerchantHomeInfoRun({
      selectType: 3,
      merchantId,
      userId,
      selectTime,
      dateType: "today",
    });
  } else if (tabIndex === 2) {
    // 点击"金额" tab，调用 selectType=4
    console.log("🚀 调用接口 selectType=4 (金额明细)");
    await getMerchantHomeInfoRun({
      selectType: 4,
      merchantId,
      userId,
      selectTime,
      dateType: "today",
    });
  }
};

// 处理昨日数据 tab 切换
const handleYesterdayTabChange = async (tabIndex) => {
  console.log("🔄 昨日数据 Tab 切换:", tabIndex);

  // 获取当前店铺 ID 和用户 ID
  const merchantId = Number(storeStore.storeId) || 0;
  const userId = userStore.userId || "";
  const selectTime = getYesterdayDate();

  // tabIndex: 0=营业额, 1=订单数, 2=金额
  if (tabIndex === 0) {
    // 点击"营业额" tab，调用 selectType=2
    console.log("🚀 调用接口 selectType=2 (昨日营业额明细)");
    await getMerchantHomeInfoRun({
      selectType: 2,
      merchantId,
      userId,
      selectTime,
      dateType: "yesterday",
    });
  } else if (tabIndex === 1) {
    // 点击"订单数" tab，调用 selectType=3
    console.log("🚀 调用接口 selectType=3 (昨日订单数明细)");
    await getMerchantHomeInfoRun({
      selectType: 3,
      merchantId,
      userId,
      selectTime,
      dateType: "yesterday",
    });
  } else if (tabIndex === 2) {
    // 点击"金额" tab，调用 selectType=4
    console.log("🚀 调用接口 selectType=4 (昨日金额明细)");
    await getMerchantHomeInfoRun({
      selectType: 4,
      merchantId,
      userId,
      selectTime,
      dateType: "yesterday",
    });
  }
};
</script>

<style lang="scss" scoped>
page {
  background: #f8f8f8;
}
.container {
  padding-bottom: 20rpx;
}
.statistical-time {
  position: relative;
  padding-left: 15rpx;
  &::after {
    content: "*";
    position: absolute;
    color: #ff0031;
    left: 0;
  }
}
.coupons {
  position: relative;
  text-align: center;
  &::after {
    position: absolute;
    content: "";
    display: block;
    height: 50rpx;
    width: 2rpx;
    background-color: #9c9c9c;
    bottom: 8rpx;
    left: -10rpx;
  }
}

// 4列网格：每一行的第一个不显示分割线 (1, 5, 9, 13...)
.grid-cols-4 .coupons:nth-child(4n + 1)::after {
  display: none;
}

// 3列网格：每一行的第一个不显示分割线 (1, 4, 7, 10...)
.grid-cols-3 .coupons:nth-child(3n + 1)::after {
  display: none;
}

// 统计范围弹框样式
.statistics-modal {
  background: #fff;
  border-radius: 16rpx;
  width: 680rpx;
  overflow: hidden;
}

.modal-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10rpx 32rpx;
  border-bottom: 1rpx solid #f5f5f5;
}

.modal-title {
  font-size: 32rpx;
  color: #333;
  font-weight: 500;
}

.modal-content {
  padding: 32rpx;
  text-align: center;
}

.business-alliance {
  margin-bottom: 32rpx;
}

.alliance-title {
  font-size: 32rpx;
  color: #333;
  font-weight: 500;
  line-height: 1.5;
}

.order-types {
  margin-bottom: 20rpx;
  line-height: 1.8;

  &:last-child {
    margin-bottom: 0;
  }
}

.order-type-item {
  font-size: 28rpx;
  color: #666;
  line-height: 1.8;
}
</style>
